<template>
  <a-form
      :model="ruleForm"
      v-bind="layout"
      :rules="rules"
      @finish="handleFinish"
  >
    <a-form-item label="样品名称" name="sample_name">
      <a-input v-model:value="ruleForm.sample_name" />
    </a-form-item>
    <a-form-item label="合金代码" name="alloy_code">
      <a-select
        v-model:value="ruleForm.alloy_code"
        style="width: 120px"
        ref="select"
      >
        <a-select-option
          v-for="item in alloyCodeSelectionOptions"
          :key="item.url"
        >
          {{ item.label }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="数据来源" name="data_source">
      <a-input v-model:value="ruleForm.data_source" />
    </a-form-item>
    <a-form-item label="样品状态" name="sample_status">
      <a-input v-model:value="ruleForm.sample_status" />
    </a-form-item>
    <a-form-item label="设备名称" name="equipment_name">
      <a-input v-model:value="ruleForm.equipment_name" />
    </a-form-item>
    <a-form-item label="设备厂家" name="equipment_manufacturer">
      <a-input v-model:value="ruleForm.equipment_manufacturer" />
    </a-form-item>
    <a-form-item label="设备型号" name="device_model">
      <a-input v-model:value="ruleForm.device_model" />
    </a-form-item>
    <a-form-item label="封装方式" name="encapsulation_way">
      <a-input v-model:value="ruleForm.encapsulation_way" />
    </a-form-item>
    <a-form-item label="助焊剂类型" name="flux_type">
      <a-input v-model:value="ruleForm.flux_type" />
    </a-form-item>
    <a-form-item label="温度" name="temperature">
      <a-input v-model:value="ruleForm.temperature" />
    </a-form-item>
    <a-form-item label="耗时" name="cost_time">
      <a-input v-model:value="ruleForm.cost_time" />
    </a-form-item>
    <a-form-item label="跌落寿命" name="falling_life">
      <a-input v-model:value="ruleForm.falling_life" />
    </a-form-item>
    <a-form-item label="跌落冲击性能曲线" name="drop_impact_performance_curve">
      <a-input v-model:value="ruleForm.drop_impact_performance_curve" />
    </a-form-item>
    <a-form-item label="热疲劳循环区间值" name="thermal_fatigue_cycle_interval">
      <a-input v-model:value="ruleForm.thermal_fatigue_cycle_interval" />
    </a-form-item>
    <a-form-item label="热循环次数" name="thermal_cycles">
      <a-input v-model:value="ruleForm.thermal_cycles" />
    </a-form-item>
    <a-form-item label="热疲劳循环失效率" name="thermal_fatigue_cycle_failure">
      <a-input v-model:value="ruleForm.thermal_fatigue_cycle_failure" />
    </a-form-item>
    <a-form-item label="韧脆转变温度" name="ductile_brittle_shift_temperature">
      <a-input v-model:value="ruleForm.ductile_brittle_shift_temperature" />
    </a-form-item>


    <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
      <a-button type="primary" :loading="submitting" html-type="submit">
        {{ submitting ? '提交中' : '确定' }}
      </a-button>
    </a-form-item>
  </a-form>
</template>
<script>
import { message } from 'ant-design-vue'

export default {
  name: 'AddOrEditMacroMorphology',
  // url !== ''则为编辑操作，否则为添加
  props: ['url'],
  emits: ['operate-success', 'operate-failed'],

  data() {

    // let isValidStr = (str) => {
    //   return str.indexOf(" ") === -1;
    // };
    // let validateSampleName = async (rule, value) => {
    //   if (value === "") {
    //     return Promise.reject("请输入样品名称");
    //   } else {
    //     if (!isValidStr(value)) {
    //       return Promise.reject("样品名称含有非法字符");
    //     }
    //     return Promise.resolve();
    //   }
    // };

    let validateAlloyCode = async (rule, value) => {
      if (value === "") {
        return Promise.reject("请选择合金代码");
      }
    };

    return {
      ruleForm: {
        sample_name: '',
        alloy_code: '',
        data_source: '',
        sample_status: '',
        equipment_name: '',
        equipment_manufacturer: '',
        device_model: '',
        encapsulation_way: '',
        flux_type: '',
        temperature: '',
        cost_time: '',
        falling_life: '',
        drop_impact_performance_curve: '',
        thermal_fatigue_cycle_interval: '',
        thermal_cycles: '',
        thermal_fatigue_cycle_failure: '',
        ductile_brittle_shift_temperature: '',
      },
      rules: {
       //  sample_name: [
       //    {
       //      validator: validateSampleName,
       //      trigger: "change",
       //      required: true,
       //      whitespace: true,
       //    },
       // ],
        alloy_code:[
          {
            validator: validateAlloyCode,
            trigger: "change",
            required: true,
            whitespace: true,
          }
        ],
      },
      layout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 14 },
      },
      submitting: false,
      alloyCodeSelectionOptions: [],
      headers: {
        authorization: 'authorization-text',
      },
    }
  },
  mounted() {
    this.fetch()
  },
  methods: {
    // 从后端获取数据
    fetch() {
      this.data =[]
      this.alloyCodeSelectionOptions = []
      this.axios
        .get('/attachment_management/alloy_phase_diagram/')
        .then((res) => {
          const data = res.data
          for (let i = 0; i < data.length; ++i) {
            this.alloyCodeSelectionOptions.push({
              url: data[i].url,
              label: data[i].alloy_code,
            })
          }
          // this.ruleForm.alloy_code = data.length === 0 ? '' : data[0].url
          if (this.url !== '') {
            this.axios
              .get(this.url)
              .then((res) => {
                const data = res.data
                this.ruleForm.sample_name = data.sample_name
                this.ruleForm.alloy_code = data.alloy_code
                this.ruleForm.data_source  = data.data_source
                this.ruleForm.sample_status  = data.sample_status
                this.ruleForm.equipment_name  = data.equipment_name
                this.ruleForm.equipment_manufacturer = data.equipment_manufacturer
                this.ruleForm.device_model = data.device_model
                this.ruleForm.encapsulation_way = data.encapsulation_way
                this.ruleForm.flux_type = data.flux_type
                this.ruleForm.temperature = data.temperature
                this.ruleForm.cost_time = data.cost_time
                this.ruleForm.falling_life = data.falling_life
                this.ruleForm.drop_impact_performance_curve = data.drop_impact_performance_curve
                this.ruleForm.thermal_fatigue_cycle_interval = data.thermal_fatigue_cycle_interval
                this.ruleForm.thermal_cycles = data.thermal_cycles
                this.ruleForm.thermal_fatigue_cycle_failure = data.thermal_fatigue_cycle_failure
                this.ruleForm.ductile_brittle_shift_temperature = data.ductile_brittle_shift_temperature

              })
              .catch((error) => {
                console.log('Error', error.message)
              })
          }
        })
        .catch((error) => {
          console.log('Error', error.message)
          this.ruleForm.alloy_code = ''
        })
    },
    handleFinish(values) {
      this.submitting = true

      const formData = new FormData()
      formData.append('sample_name', values.sample_name)
      formData.append('alloy_code', values.alloy_code)
      formData.append('data_source', values.data_source)
      formData.append('sample_status', values.sample_status)
      formData.append('equipment_name', values.equipment_name)
      formData.append('equipment_manufacturer', values.equipment_manufacturer)
      formData.append('device_model', values.device_model)
      formData.append('encapsulation_way', values.encapsulation_way)
      formData.append('flux_type', values.flux_type)
      formData.append('temperature', values.temperature)
      formData.append('cost_time', values.cost_time)
      formData.append('falling_life', values.falling_life)
      formData.append('drop_impact_performance_curve', values.drop_impact_performance_curve)
      formData.append('thermal_fatigue_cycle_interval', values.thermal_fatigue_cycle_interval)
      formData.append('thermal_cycles', values.thermal_cycles)
      formData.append('thermal_fatigue_cycle_failure', values.thermal_fatigue_cycle_failure)
      formData.append('ductile_brittle_shift_temperature', values.ductile_brittle_shift_temperature)
      if (this.url !== '') {
        this.axios
          .put(this.url, formData)
          .then(() => {
            this.submitting = false
            message.success('修改成功！')
            this.$emit('operate-success')
          })
          .catch((error) => {
            this.submitting = false
            message.error('修改失败！')
            this.$emit('operate-failed')
            console.log('Error', error.message)
          })
      } else {
        this.axios
          .post('/property_management/service_property/', formData)
          .then(() => {
            this.submitting = false
            message.success('添加成功！')
            this.$emit('operate-success')
          })
          .catch((error) => {
            this.submitting = false
            message.error('添加失败！')
            this.$emit('operate-failed')
            console.log('Error', error.message)
          })
      }
    },
  },
}
</script>
